package com.ft.core.utils.validate.impl;

import com.ft.core.enums.IEnumIntValue;
import com.ft.core.utils.validate.EnumIntValueRange;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @copyright (C), 2015-2019, XXX有限公司
 * @fileName: EnumIntValueRangeValidatorImpl
 * @author: 李阳
 * @date: 2019/6/27 4:36
 * @description: IEnumIntValue枚举值范围验证实现
 * @history: <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
public class EnumIntValueRangeValidatorImpl implements ConstraintValidator<EnumIntValueRange, IEnumIntValue> {

    private long min;
    private long max;
    private boolean allowNull;

    @Override
    public void initialize(EnumIntValueRange constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
        this.allowNull = constraintAnnotation.allowNull();
    }

    @Override
    public boolean isValid(IEnumIntValue value, ConstraintValidatorContext context) {
        if (null != value) {
            final int index = value.getValue();
            return index >= min && index <= max;
        }
        if (this.allowNull) {
            return true;
        }
        return false;
    }
}
